package com.ruoyi.framework.config.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    private TokenService tokenService;

    @Override
    public void insertFill(MetaObject metaObject) {
        if(ServletUtils.getRequestAttributes() != null){
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            if(loginUser!=null){
                //创建用户
                this.strictInsertFill(metaObject, "createBy", String.class,loginUser.getUsername());
                //创建时间
                this.strictInsertFill(metaObject, "createTime",Date.class, new Date());
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if(ServletUtils.getRequestAttributes() != null){
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

            if(loginUser!=null) {

                if (metaObject.hasSetter("updateBy")) {
                    metaObject.setValue("updateBy", null);
                }
                if (metaObject.hasSetter("updateTime")) {
                    metaObject.setValue("updateTime", null);
                }

                //创建用户
                this.strictUpdateFill(metaObject, "updateBy", String.class, loginUser.getUsername());
                //创建时间
                this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
            }
        }
    }
}
